

function saveLoadInit(){
	
	handlers.saveClick = function(){ save(); };
		document.getElementById("saveButton").addEventListener("click", handlers.saveClick, false);
		
	handlers.loadClick = function(){ loadClick(); };
		document.getElementById("loadButton").addEventListener("click", handlers.loadClick, false);

	window.saveObject = {};
}


/*********************************************SAVE*****************************/

//traverse tree recursively, saving at each node along the way

function save(){
	
	saveObject = {};
	saveObject.title = claim.displayedDiv.innerText.trim();  //this will be used for the SQL database

	saveFruits();
	saveGoals();
	savePremises();
	saveReasons();
	
	saveToDB(saveObject);
	
	//console.log(saveObject);
	//console.log(JSON.stringify(saveObject) );
}

function saveToDB(saveObject){

	var xmlhttp = new XMLHttpRequest();
	
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			//do stuff here
			//document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
			//console.log( xmlhttp.responseText);
			//alert( xmlhttp.responseText);
		}
	}

	//****this will have to be changed when upload to live server
	//it would be cool if I could put an IF statement here to automatically pick the right one,
		//so same file for remote and local server
	xmlhttp.open("POST", "http://127.0.0.1:80/DEApp/php/saveMap.php", true);
	//xmlhttp.open("POST", "localhost/saveMap.php", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.send("title=" + saveObject.title + '&map=' + JSON.stringify(saveObject) );
}

//saving Fruits, goals, and premises is different than reasons because can just use DOM tree
function saveFruits(){
	saveObject.fruits =[];
	
	//not all of the divs in the container are fruits, some are buttons, which we don't want
	var saveFruits = fruitsContainer.getElementsByClassName("fruit");
	
	for(var i=0,j=saveFruits.length; i<j; i++){
	  saveObject.fruits[i] = {};
	  saveObject.fruits[i].contents = saveFruits[i].innerText.trim();
	};
}

function saveGoals(){
	saveObject.goals =[];
	
	var saveGoals = goalsContainer.getElementsByClassName("goal");
	
	for(var i=0,j=saveGoals.length; i<j; i++){
	  saveObject.goals[i] = {};
	  saveObject.goals[i].contents = saveGoals[i].innerText.trim();
	};
}

function savePremises(){
	saveObject.premises = [];

	var savePremises = premisesContainer.getElementsByClassName("premise");

	for(var i=0,j=savePremises.length; i<j; i++){
	  saveObject.premises[i] = {};
	  saveObject.premises[i].contents = savePremises[i].innerText.trim();
	};
}

//different process than saving others because use node tree instead of DOM tree
//needs fixing to implement saving assist nodes, logical fallacies, node type
function saveReasons(){

	saveObject.reasons =[];
	saveObject.reasons[0] = {};
	var currentObject = saveObject.reasons[0];

	traverseTree(claim, currentObject);  //start with claim A0
}

//call appendSave, then recursively call traverseTree in each childNode
function traverseTree(currentNode, currentObject){

	//save yourself, then have each one of your assists and children save themselves
	currentObject.contents = currentNode.displayedDiv.innerText.trim();
	currentObject.logicalFallacy = returnFallacy(currentNode);
	currentObject.type = returnType(currentNode);
	currentObject.assists = [];
	
	//save assists
	//loop through all assists, calling this function for each one
	var indexA = 0;
	while(currentNode.assists[indexA]){
		currentObject.assists[indexA] = {};
		traverseTree(currentNode.assists[indexA],currentObject.assists[indexA] );
		indexA++;
	}

	//save children
	//loop through all children, calling this function for each one of them
	var indexR = 0;
	currentObject.children = [];
	
	while( currentNode.children[indexR] ){
		currentObject.children[indexR] = {};
		traverseTree(currentNode.children[indexR], currentObject.children[indexR] );

		indexR++;
	}

	return;
}

function returnFallacy(currentNode){
	if (currentNode.fallacyLabel) {return currentNode.fallacyLabel.innerText;}
	else{
		return "None";
	}
}

function returnType(currentNode){
	if(currentNode.displayedDiv.classList.contains("claim") ) return "claim";
	if(currentNode.displayedDiv.classList.contains("support") ) return "support";
	if(currentNode.displayedDiv.classList.contains("attack") ) return "attack";
	if(currentNode.displayedDiv.classList.contains("evidence") ) return "evidence";
	if(currentNode.displayedDiv.classList.contains("assist") ) return "assist";
	if(currentNode.displayedDiv.classList.contains("rebuttal") ) return "rebuttal";
}

/*********************************************LOAD*****************************/

function loadClick(){

	//display titles of maps that have been saved to database
	//user picks one
	//load that one
	
	retrieveTitles();
	
}

function retrieveTitles() {
	var xmlhttp = new XMLHttpRequest();
	
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			//do stuff here
			//save returned array to "titles"

			//var titles = new Array(xmlhttp.responseText);
			//FIX ** figure out a way to not have to use eval()
			var titles = eval(xmlhttp.responseText);
			
			//console.log( xmlhttp.responseText);
			//console.dir( titles );
			//alert( xmlhttp.responseText);
			//alert(titles[0]);
			
			createForm(titles);
			
			//set an event listener on document.body.  If click, remove loadDropDown
			handlers.neglectLoadForm = function(event){
				//if they didn't click on the form, then remove it, else, do nothing
					//since they are making selection
				if(event.target.tagName != "SELECT"){
					document.body.removeChild( document.getElementById("loadFormDrop") );
					document.removeEventListener("click", handlers.neglectLoadForm, false);
				}
			};
			document.addEventListener("click", handlers.neglectLoadForm, false);
		}
	}

	//****this will have to be changed when upload to live server
	//it would be cool if I could put an IF statement here to automatically pick the right one,
		//so same file for remote and local server
	xmlhttp.open("POST", "http://127.0.0.1:80/DEApp/php/load.php", true);
	//xmlhttp.open("POST", "localhost/load.php", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.send();
}

function createForm(titles){
	var loadFormDrop = document.createElement('form');
		loadFormDrop.id = "loadFormDrop";
		//loadFormDrop.action = "http://127.0.0.1:80/DEApp/php/retrieveMap.php";
		//loadFormDrop.enctype = "application/x-www-form-urlencoded";
		//loadFormDrop.method = "POST";
		//loadFormDrop.name = "loadFormDrop";
		document.body.appendChild( loadFormDrop );
		
	var selectObject = document.createElement('select');
		selectObject.onchange = function () {
			getSelection(this.value);
		};
		//selectObject.size = 10;
		loadFormDrop.appendChild( selectObject );
	
	//make an empty option to start with - this makes onchage work better since it won't do anything if
		//you want to select the first one
	var optionToAdd = document.createElement("option");
	selectObject.add( optionToAdd, null);
	
	for(var i=0,j=titles.length; i<j; i++){
		optionToAdd = document.createElement("option");
		optionToAdd.text = titles[i];
		selectObject.add( optionToAdd, null);	
	};
	
	return loadFormDrop;
}

function getSelection(selection){
	
	//remove drop down menu
	document.body.removeChild( document.getElementById("loadFormDrop") );
	//remove listener on body that would remove loadForm if clicked elsewhere
	document.removeEventListener("click", handlers.neglectLoadForm, false);
	
	var xmlhttp = new XMLHttpRequest();
	
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

			console.log(xmlhttp.responseText);
			console.dir( JSON.parse( xmlhttp.responseText) );

			load( JSON.parse(xmlhttp.responseText) );
			
		}
	}

	//****this will have to be changed when upload to live server
	//it would be cool if I could put an IF statement here to automatically pick the right one,
		//so same file for remote and local server
	xmlhttp.open("POST", "http://127.0.0.1:80/DEApp/php/retrieveMap.php", true);
	//xmlhttp.open("POST", "localhost/load.php", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.send("title=" + selection);
}

function load(map){

	clearExisting();

	saveObject = map;
	
	loadFruits();
	loadGoals();
	loadPremises();
	loadReasons();
}

//clear old stuff///////////////////
function clearExisting(){
	//removes all SVG lines
	paper.clear();
	
	//reset NODES, which are separate from the DOM
	claim = null;

	clearFruits();
	clearGoals();
	clearPremises();
	clearReasons();
}

function clearFruits(){
	
	//not all of the divs in that div are fruits, some are buttons, which we don't want
	var oldFruits = fruitsContainer.getElementsByClassName("fruit");
	
	//the NodeList gets updated each time a node is removed, so this will keep knocking them off
	while(oldFruits[0]){
		fruitsContainer.removeChild(oldFruits[0] );
	}
}

function clearGoals(){
	
	//not all of the divs in that div are goals, some are buttons, which we don't want
	var oldGoals = goalsContainer.getElementsByClassName("goal");
	
	//the NodeList gets updated each time a node is removed, so this will keep knocking them off
	while(oldGoals[0]){
		goalsContainer.removeChild(oldGoals[0] );
	}
}

function clearPremises(){
	
	//not all of the divs in that div are premises, some are buttons, which we don't want
	var oldPremises = premisesContainer.getElementsByClassName("premise");
	
	//the NodeList gets updated each time a node is removed, so this will keep knocking them off
	while(oldPremises[0]){
		premisesContainer.removeChild(oldPremises[0] );
	}
}

function clearReasons(){
	
	var oldReasons = argumentsContainer.getElementsByClassName("argument");
	//the NodeList gets updated each time a node is removed, so this will keep knocking them off
	while(oldReasons[0]){
		argumentsContainer.removeChild(oldReasons[0] );
	}
}

//start loading///////////////

function loadFruits(){

	for(var i=0,j=saveObject.fruits.length; i<j; i++){
	  newFruit(saveObject.fruits[i] );
	};
}

function loadGoals(){
	
	for(var i=0,j=saveObject.goals.length; i<j; i++){
	  newGoal(saveObject.goals[i] );
	};
}
function loadPremises(){
	
	for(var i=0,j=saveObject.premises.length; i<j; i++){
	  newPremise(saveObject.premises[i] );
	};
}

function loadReasons(){

	var currentObject = saveObject.reasons[0];
	
	claim = newClaim(currentObject);

	spawnAll(claim, currentObject);  //start with claim
}

//call appendSave, then recursively call traverseTree in each childNode
function spawnAll(spawner, currentObject){

	//spawn all of your children and assists, and have them do the same

	//loop through all assists, calling this function for each one
	var indexA = 0;
	var spawned;  //the child that was just spawned
	while(currentObject.assists[indexA]){
		spawned = spawner.spawnChild(currentObject.assists[indexA].type, currentObject.assists[indexA]);
		spawnAll(spawned, currentObject.assists[indexA]);
		indexA++;
	}

	//loop through all children, calling this function for each one of them
	var indexC = 0;
	while(currentObject.children[indexC] ){
		spawned = spawner.spawnChild(currentObject.children[indexC].type, currentObject.children[indexC]);
		spawnAll(spawned, currentObject.children[indexC]);
		indexC++;
	}

	return;
}
